from time import time


class Timer:
    def __init__(self):
        self.start = None
        self.end = None
        self.elapsed = None

    def _format_time(self, seconds):
        """格式化时间
        """
        if seconds < 1:
            return f"{seconds * 1000:.2f} ms"
        elif seconds < 60:
            return f"{seconds:.2f} s"
        elif seconds < 3600:
            return f"{seconds / 60:.2f} min"
        else:
            return f"{seconds / 3600:.2f} h"

    def __enter__(self):
        self.start = time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time()
        self.elapsed = self.end - self.start
        print(f"Elapsed time: {self._format_time(self.elapsed)}")